package com.sweets.look.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import com.sweets.look.R;
import com.sweets.look.adapter.HistoryItem;
import com.sweets.look.adapter.RuleItem;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "sweets";
    private static final int DATABASE_VERSION = 1;
    private static final String KEY_ID = "id";
    private static final String KEY_TAG = "tag";
    private static final String KEY_TITLE = "title";
    private static final String KEY_URL = "url";
    private static final String TABLE_ADS = "ads";
    private static final String TABLE_HISTORY = "history";
    private static SQLiteDatabase mDatabase;

    public DatabaseHandler(Context context) {
        super(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);
        mDatabase = this.getWritableDatabase();
    }

    public synchronized void close() {
        if (mDatabase != null) {
            mDatabase.close();
        }
        super.close();
    }

    public synchronized void deleteAdsItem(String url) {
        mDatabase.delete(TABLE_ADS, "url = ?", new String[]{url});
    }

    public void deleteAllAdRules() {
        mDatabase.delete(TABLE_ADS, null, null);
    }

    public synchronized void deleteAllHistoryItems() {
        mDatabase.delete(TABLE_HISTORY, null, null);
    }

    public synchronized void deleteHistoryItem(String url) {
        mDatabase.delete(TABLE_HISTORY, "url = ?", new String[]{url});

    }

    public List<HistoryItem> findItemsContaining(String search) {
        ArrayList<HistoryItem> data = new ArrayList<>();
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM history WHERE title LIKE \'%" +
                search + "%\' OR " + KEY_URL + " LIKE \'%" + search + "%\' LIMIT 5", null);
        int i = 0;
        if (cursor.moveToLast()) {
            do {
                HistoryItem item = new HistoryItem();
                item.setID(Integer.parseInt(cursor.getString(0)));
                item.setUrl(cursor.getString(1));
                item.setTitle(cursor.getString(2));
                item.setImageId(R.drawable.ic_history);
                data.add(item);
                ++i;
                if ((cursor.moveToPrevious()) && i < 5) {
                    continue;
                }

                break;
            } while (true);
        }

        cursor.close();
        return data;
    }

    public List<RuleItem> getAllAdsItems() {
        ArrayList<RuleItem> data = new ArrayList<>();
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM ads", null);
        if (cursor.moveToFirst()) {
            do {
                RuleItem item = new RuleItem();
                item.setUrl(cursor.getString(cursor.getColumnIndex(KEY_URL)));
                item.setTags(cursor.getString(cursor.getColumnIndex(KEY_TAG)));
                item.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
                data.add(item);
                if (cursor.moveToNext()) {
                    continue;
                }

                break;
            } while (true);
        }

        cursor.close();
        return data;
    }

    public List<HistoryItem> getAllHistoryItems() {
        ArrayList<HistoryItem> data = new ArrayList<>();
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM history", null);
        if (cursor.moveToFirst()) {
            do {
                HistoryItem v1 = new HistoryItem();
                v1.setID(Integer.parseInt(cursor.getString(0)));
                v1.setUrl(cursor.getString(1));
                v1.setTitle(cursor.getString(2));
                v1.setImageId(R.drawable.ic_history);
                data.add(v1);
                if (cursor.moveToNext()) {
                    continue;
                }

                break;
            } while (true);
        }

        cursor.close();
        return data;
    }

    public int getHistoryItemsCount() {
        Cursor cursor = mDatabase.rawQuery("SELECT  * FROM history", null);
        cursor.close();
        return cursor.getCount();
    }

    public List<HistoryItem> getLastHundredItems() {
        ArrayList<HistoryItem> data = new ArrayList<>();
        Cursor cursor = mDatabase.rawQuery("SELECT  * FROM history", null);
        int i = 0;
        if (cursor.moveToLast()) {
            do {
                HistoryItem item = new HistoryItem();
                item.setID(Integer.parseInt(cursor.getString(0)));
                item.setUrl(cursor.getString(1));
                item.setTitle(cursor.getString(2));
                item.setImageId(R.drawable.ic_history);
                data.add(item);
                ++i;
                if (cursor.moveToPrevious() && i < 200) {
                    continue;
                }

                break;
            } while (true);
        }

        cursor.close();
        return data;
    }

    public synchronized String getMatchTag(String url) {

        String tag = null;
        Cursor cursor = mDatabase.query(TABLE_ADS, new String[]{KEY_ID, KEY_URL, KEY_TAG}, "url=?",
                new String[]{url}, null, null, null, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                tag = cursor.getString(2);
            }

            cursor.close();
        }
        return tag;
    }

    public boolean isOpen() {
        return mDatabase != null && mDatabase.isOpen();
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE history(id INTEGER PRIMARY KEY,url TEXT,title TEXT)");
        db.execSQL("CREATE TABLE ads(id INTEGER PRIMARY KEY,url TEXT,tag TEXT)");
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS history");
        this.onCreate(db);
    }

    public synchronized void visitAdsItem(String url, String tag, boolean wipe) {
        ContentValues contentValues;
        Cursor cursor = mDatabase.query(TABLE_ADS, new String[]{KEY_ID, KEY_URL, KEY_TAG}, "url=?",
                new String[]{url}, null, null, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                if (!cursor.getString(2).equalsIgnoreCase(tag) && !wipe) {
                    tag +=  ", " + cursor.getString(2);
                }

                contentValues = new ContentValues();
                contentValues.put(KEY_TAG, tag);
                mDatabase.update(TABLE_ADS, contentValues, "url=?", new String[]{url});
            } else {
                contentValues = new ContentValues();
                contentValues.put(KEY_URL, url);
                contentValues.put(KEY_TAG, tag);
                mDatabase.insert(TABLE_ADS, null, contentValues);
            }

            cursor.close();
            return;
        }

        contentValues = new ContentValues();
        contentValues.put(KEY_URL, url);
        contentValues.put(KEY_TAG, tag);
        mDatabase.insert(TABLE_ADS, null, contentValues);
    }

    public synchronized void visitHistoryItem(String url, String title) {

        mDatabase.delete(TABLE_HISTORY, "url = ?", new String[]{url});
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_URL, url);
        contentValues.put(KEY_TITLE, title);
        mDatabase.insert(TABLE_HISTORY, null, contentValues);
    }
}

